from django.contrib import admin
from django.utils.html import format_html

from user.models import UserInfo

# Register your models here.
from libs.CommonAdmin import BaseModelAdmin


# 创建一个类并用它来定制UserInfo
@admin.register(UserInfo)
# 这个类必须继承 admin.ModelAdmin
class UserInfoAdmin(admin.ModelAdmin):
    # 默认用户的顺序是倒叙,如果想正序添加属性
    ordering = ["id"]

    # 想要对某个字段渲染样式
    def display_avatar(self, obj):
        # 获取avatar路径
        avatar_path = obj.avatar if obj.avatar else 'media/avatar/default.jpg'

        avatar_url = f'http://127.0.0.1:8000/media/{avatar_path}'

        return format_html(
            f'<a href="{avatar_url}" target="_blank">'
            f'<img src="{avatar_url}" alt="请稍后再试哦" style="width: 50px;height: auto">'
            f'</a>')

    display_avatar.short_description = "用户头像"
    # 后台展示的信息，默认是全部都展示，但是可以定制展示的字段
    list_display = ["id", 'username', 'last_name', 'email', 'phone', 'display_avatar', 'create_time',
                    'is_deleted', 'blog']
